//
//  UIColor+Extension.m
//  UI-02-Color
//
//  Created by Apple on 16/3/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "UIColor+Extension.h"

@implementation UIColor (Extension)

+ (instancetype)kk_colorWithHex:(u_int32_t)hex {
    
    // 0xFFAA99
    int red = (hex & 0xFF0000) >> 16;
    // 0x00FF00
    // => 0x00AA00 => 0x0000AA
    int green = (hex & 0x00FF00) >> 8;
    // 0x1111 1111 AA 1001 1001
    // 0x0000 0000 00 1111 1111
    int blue = hex & 0x0000FF;
    
    return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0];
}

/** 16进制(字符串形式) 返回 图片 */
+ (UIImage *)imageWithString:(NSString *)string {
    
    return [self imageWithColor:[self colorWithString:string]];
}
/** 16进制返回颜色 */
+ (UIColor *)colorWithString:(NSString *)string {
    CGFloat alpha = 1.0f;
    NSNumber * red = @0.0;
    NSNumber * green = @0.0;
    NSNumber * blue = @0.0;
    
    NSMutableArray<NSNumber *> * colors = [NSMutableArray arrayWithArray:@[ red, green, blue ]];
    
    unsigned hexComponent;
    NSString * colorString = [string uppercaseString];
    for (int i = 0; i < colors.count; i++) {
        NSString * substring = [colorString substringWithRange:NSMakeRange(i * 2, 2)];
        
        [[NSScanner scannerWithString:substring] scanHexInt:&hexComponent];
        
        NSNumber * temp = colors[i];
        temp = @(hexComponent / 255.0);
        colors[i] = temp;
    }
    
    return [UIColor colorWithRed:[colors[0] floatValue] green:[colors[1] floatValue] blue:[colors[2] floatValue] alpha:alpha];
}
/** 颜色 返回 图片 */
+ (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end
